package com.example.stmall.manager.mapper;

import com.example.stmall.manager.entity.Category;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 分类的Mapper层接口
 * 基于注解的开发
 */
@Mapper     //MyBatis的注解，当前的接口是MyBatis的接口，相当于在Application添加@MapperScan注解
public interface CategoryMapper {
    /**
     * 插入数据表的操作
     * 1.返回值类型：int
     * 2.方法名：insert
     * 3.参数：category
     * 4.配置：使用@Insert注解配置SQL语句
     */
    @Insert({"insert into category",
            "(name,dscp,pic,parent_id,recom)",
            "value(#{name},#{dscp},#{pic},#{parentId},#{recom})"})
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")   //获得自增主键
    int insert(Category category);

    /**
     * 根据ID删除
     */
    @Delete("delete from category where id =#{id}")
    int delete(Integer id);

    /**
     * 根据ID更新,使用动态SQL，需要为SQL添加<script></script>
     */
    @Update({"<script>",
            "update category",
            "<set>",
            "<if test= 'name != null and name.length>0'>name=#{name},</if>",
            "<if test= 'dscp != null and dscp.length>0'>dscp=#{dscp},</if>",
            "<if test= 'pic != null and pic.length>0'>pic=#{pic},</if>",
            //判断参数category的parentId属性不为空
            //设置数据表的parent_id字段 为 参数category的parentId属性
            "<if test= 'parentId != null'>parent_id=#{parentId},</if>",
            "<if test= 'recom != null'>recom=#{recom}</if>",
            "</set>",
            "where id =#{id}",
            "</script>"
    })
    int update(Category category);

    /**
     * 根据ID查询
     */
    @Select("select * from category where id=#{id}")
    Category selectById(Integer id);

    /**
     * 通用的多条件的组合查询
     */
    @Select({"<script>",
            "select * from category",
            "<where>",
            "<if test= 'name != null and name.length>0'> name like '%${name}%'</if>",
            "<if test= 'parentId != null and parentId != 0'> and parent_id=#{parentId}</if>",
            "<if test= 'parentId != null and parentId == 0'> and parent_id is null </if>",
            "<if test = 'recom != null'> and recom=#{recom}</if>",
            "<if test = 'status != null'> and status=#{status}</if>",
            "</where>",
            "</script>"})
    @Results({      //相当于<resultMap>标签
        @Result(column = "parent_id",property = "parentId"),
        @Result(column = "parent_id",property = "parent",
            one=@One(select="selectById"))   //相当于<id>和<result>标签
    })
    List<Category> select(Category category);
}
